﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MySystemMag.Models;
using MySystemMag.DAL;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;

namespace MySystemMag.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class LoginController : ControllerBase
    {
        private TaxContext conn;
        private IJWTService JWTService = null;//注入IJWTService接口
        public LoginController(TaxContext _conn,IJWTService _JWTService)
        {
            conn = _conn;
            JWTService = _JWTService;
        }
        [AllowAnonymous]
        [HttpPost, Route("LoginIn")]
        public async Task<Res<LoginData>> LoginIn(LoginInput Input)
        {
            var res = new Res<LoginData>();
            try
            {
                if (!string.IsNullOrWhiteSpace(Input.LoginName) && !string.IsNullOrWhiteSpace(Input.LoginPass))
                {
                    var user = await conn.User.FirstOrDefaultAsync(b => b.LoginName == Input.LoginName && b.LoginPWD == Input.LoginPass);
                    if (user != null)
                    {
                        var logindata = new LoginData();
                        logindata.LoginToken = JWTService.GetToken(user.UserID,user.LoginPWD);
                        logindata.LoginName = user.LoginName;
                        logindata.UserID = user.UserID;
                        logindata.UserName = user.UserName;
                        logindata.Sex = user.Sex;
                        var menulist = conn.Menu.ToList();
                        logindata.menu= MenuFunction.GetMenuList(menulist);
                        res.code = "0000";
                        res.msg = "成功";
                        res.data = logindata;

                    }
                    else
                    {
                        res.code = "0001";
                        res.msg = "账号或者密码错误";
                    }
                }
                else
                {
                    res.code = "0002";
                    res.msg = "请输入账号或者密码";
                }
            }
            catch (Exception ex)
            {
                res.code = "9999";
                res.msg = ex.ToString();
            }
             return res;
        }
        
        [HttpPost, Route("Test")]
        public async Task<Res<string>> Test(LoginInput Input)
        {
            var res = new Res<string>();
            res.code = "0000";
            res.msg = "test";
            res.data = "test";
            return res;
        }
    }
}
